package com.egg.ylt.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.CustomUtils;
import com.egg.ylt.Utils.MyPayResult;
import com.egg.ylt.Utils.StatusBarUtil;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.pojo.WeChatPayEntity;
import com.egg.ylt.presenter.impl.RechargePresenterImpl;
import com.egg.ylt.view.IRechargeView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yonyou.framework.library.base.BaseActivity;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.ToastUtil;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ACT_Recharge extends BaseActivity<RechargePresenterImpl> implements IRechargeView {

    @BindView(R.id.include_rl_view)
    RelativeLayout mIncludeRlView;
    @BindView(R.id.include_iv_back)
    ImageView includeIvBack;
    @BindView(R.id.include_tv_title)
    TextView includeTvTitle;
    @BindView(R.id.recharge_tv_price)
    TextView rechargeTvPrice;
    @BindView(R.id.recharge_tv_icon)
    TextView rechargeTvIcon;
    @BindView(R.id.btn_recharge)
    TextView btnRecharge;
    @BindView(R.id.edit_pay_price)
    EditText editPayPrice;
    @BindView(R.id.iv_selected_zfb)
    ImageView ivSelectedZfb;
    @BindView(R.id.ll_pay_zfb)
    LinearLayout llPayZfb;
    @BindView(R.id.iv_selected_wx)
    ImageView ivSelectedWx;
    @BindView(R.id.ll_pay_wx)
    LinearLayout llPayWx;

    /**
     * 支付宝支付渠道
     */
    private static final int SDK_PAY_FLAG = 1;
    /**
     * 微信支付渠道
     */
    private static final String appid = "wxb3b603b1b6dd65b4";
    private String payWay = "1";//支付方式 0 微信，1支付宝
    private IWXAPI msgApi;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    MyPayResult payResult = new MyPayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //支付成功，去我的次卡界面
                        ToastUtil.makeText(mContext, "支付成功", false);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //支付失败
                        ToastUtil.makeText(mContext, "支付失败,请重新支付", false);
                    }
                    break;

                }
            }
        }
    };

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_recharge;
    }

    @Override
    protected View getLoadingTargetView() {
        return null;
    }

    @Override
    protected void initViewsAndEvents() {

        StatusBarUtil.setStatusBarColor(this, R.color.ylt_whit);
        StatusBarUtil.StatusBarLightMode(this);
        CustomUtils.setImmersiveStatusBar(mContext, mIncludeRlView);

        //设置title 和 套餐卡数据
        includeTvTitle.setText("充值");

        // 将该app注册到微信
        msgApi = WXAPIFactory.createWXAPI(this, Constants.WX_APP_ID);
        msgApi.registerApp(Constants.WX_APP_ID);

        //默认支付宝充值
        ivSelectedZfb.setSelected(true);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @OnClick({R.id.include_iv_back, R.id.ll_pay_zfb, R.id.ll_pay_wx, R.id.btn_recharge})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.include_iv_back://返回键
                finish();
                break;
            case R.id.ll_pay_zfb://支付宝
                payWay = "1";
                ivSelectedWx.setSelected(false);
                ivSelectedZfb.setSelected(true);
                break;
            case R.id.ll_pay_wx://微信
                payWay = "0";
                ivSelectedWx.setSelected(true);
                ivSelectedZfb.setSelected(false);
                break;
            case R.id.btn_recharge://充值
                setPay();
                break;
        }
    }

    private void setPay() {
        String payPrice = editPayPrice.getText().toString().trim();
        if (StringUtil.isEmpty(payPrice)) {
            ToastUtil.makeText(mContext, "请输入充值金额", false);
            return;
        }
        double price = Double.valueOf(payPrice);
        if (price <= 0) {
            ToastUtil.makeText(mContext, "充值金额应大于0", false);
            return;
        }
        if (StringUtil.isEmpty(payWay)) {
            ToastUtil.makeText(mContext, "请选择支付方式", false);
            return;
        }
        if ("0".equals(payWay)) {
            //请求微信支付订单信息
//            ToastUtil.makeText(mContext, "开发中...", false);
            mPresenter.getWxOrderInfo(Constants.TOKEN, Constants.COMPANYID, payPrice);
        } else if ("1".equals(payWay)) {
            //请求支付宝支付订单信息
            mPresenter.getZfbOrderInfo(Constants.TOKEN, Constants.COMPANYID, payPrice);
        }
    }

    @Override
    public void getZfbInfo(String info) {
        //支付宝订单信息
        if (StringUtil.isEmpty(info)) {
            ToastUtil.makeText(mContext, "支付宝支付订单信息为null", false);
            return;
        }
        aliPay(info);
    }

    @Override
    public void getWxInfo(String info) {

        if (StringUtil.isEmpty(info)) {
            ToastUtil.makeText(mContext, "微信支付订单信息为null", false);
            return;
        }
        //微信支付订单信息
        WeChatPayEntity bean = new Gson().fromJson(info, WeChatPayEntity.class);
        onWXPay(bean);
    }

    //支付宝付款方法
    public void aliPay(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mContext);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    //微信支付方法
    private void onWXPay(WeChatPayEntity bean) {

        Constants.WX_PAY_TYPE = Constants.WX_PAY_RECHARGE;

        PayReq request = new PayReq();
        //微信开放平台审核通过的应用APPID
        request.appId = Constants.WX_APP_ID;
        //微信支付分配的商户号
        request.partnerId = bean.getPartnerid();
        //微信返回的支付交易会话ID
        request.prepayId = bean.getPrepayid();
        //暂填写固定值Sign=WXPay
        request.packageValue = "Sign=WXPay";
        //随机字符串，不长于32位。推荐随机数生成算法
        request.nonceStr = bean.getNoncestr();
        //时间戳
        request.timeStamp = bean.getTimestamp();
        //签名
        request.sign = bean.getSign();
//        Log.e("PayActivity", request.checkArgs()+"");//这是检查你请求参数是否有误，如果打印是false，请检查你的请求参数是否是上面的几个
//        Log.e("PayActivity",msgApi.sendReq(request)+""); //这表示能够调起api，一般上面那个成功，这个没有问题。两个Log如果打印都是true，恭喜你离成功不远了
//        ToastUtil.makeText(mContext, "正常调起支付", false);
        msgApi.sendReq(request);
//        finish();
//        Log.e("PayActivity", request.checkArgs()+"");
    }
}
